package com.rayboo.example.collections.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * HashMap示例
 *
 * @author ray
 * @since 2019/07/25
 *
 * <p>HashMap是一个基于Map的集合类，用于存储Key和value对，它表示为HashMap <Key，Value>或HashMap <K，V>。
 * 此类不保证Map的顺序。它类似于Hashtable类，除了它是不同步的并且允许空值（空值和空键）。
 *
 * <p>HashMap不是有序集合，这意味着它不会按照它们插入HashMap的顺序返回键和值。
 * 它不会对存储的键和值进行排序。必须导入java.util.HashMap或其超类才能使用HashMap类和方法。
 *
 * <p>https://beginnersbook.com/2013/12/hashmap-in-java-with-example/
 */
public class HashMapExample {

    public static void main(String args[]) {

        /* This is how to declare HashMap */
        HashMap<Integer, String> hmap = new HashMap<Integer, String>();

        /*Adding elements to HashMap*/
        hmap.put(12, "Chaitanya");
        hmap.put(2, "Rahul");
        hmap.put(7, "Singh");
        hmap.put(49, "Ajeet");
        hmap.put(3, "Anuj");

        /* Display content using Iterator*/
        Set set = hmap.entrySet();
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Map.Entry entry = (Map.Entry)iterator.next();
            System.out.print("key is: "+ entry.getKey() + " & Value is: ");
            System.out.println(entry.getValue());
        }

        /* Get values based on key*/
        String var= hmap.get(2);
        System.out.println("\nValue at index 2 is: "+var);

        /* Remove values based on key*/
        hmap.remove(3);
        System.out.println("\nMap key and values after removal:");
        Set set2 = hmap.entrySet();
        Iterator iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
            Map.Entry mentry2 = (Map.Entry)iterator2.next();
            System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
            System.out.println(mentry2.getValue());
        }

    }
}
